package com.tangding.hprose.api.server.command.impl.watch;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.tangding.cache.TableWatchingCache;
import com.tangding.common.exception.GException;
import com.tangding.common.logx.LogHelp;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.hprose.api.client.HproseAsClient;
import com.tangding.hprose.api.server.command.Command;
import com.tangding.hprose.api.server.command.Response;
import com.tangding.net.pool.BaseNettySessionPool;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年12月14日_下午7:05:20
 *
 */
@Component
public class WatchingTable implements Command{

	@Autowired
	BaseNettySessionPool pool;
	
	@SuppressWarnings("unchecked")
	@Override
	public Response exe(Object... params) throws GException {
		Map<String, Object> user = (Map<String, Object>) params[params.length - 1];
		String uid = (String) user.get("uid");
		String tableId = (String) ((Map<String, Object>) params[0]).get("tableId");
		String cancelTabelId = (String) ((Map<String, Object>) params[0]).get("cancelTabelId");
		String gameName = (String) ((Map<String, Object>) params[0]).get("gameName");
		if (!Strings.isNullOrEmpty(cancelTabelId)) {
			TableWatchingCache.remove(uid, cancelTabelId);
			Map<String, Object> cleanClient = new HashMap<>();
			cleanClient.put("gameName", gameName);
			cleanClient.put("tableId", tableId);
			
			pool.doResponse(uid, "UpdateTableDetails", cleanClient);
		}
		
		int showCondition = (Integer) ((Map<String, Object>) params[0]).get("showCondition");
//		System.out.println("push ..." + uid + " ---- " + tableId);
		TableWatchingCache.push(uid, tableId, showCondition);
		
		Map<String, Object> request = new HashMap<>();
		request.put("gameName", gameName);
		request.put("tableId", tableId);
		request.put("showCondition", showCondition);
		poolExe.submit(new Runnable() {
			public void run() {
				try {
					Object result = HproseAsClient.invoke("QueryTableDetails", request);
					if (result != null) {
						Map<String, Object> receivedData = JacksonUtil.readValue(JacksonUtil.toJson(result), Map.class);
						receivedData.put("gameName", gameName);
						receivedData.put("tableId", tableId);
						receivedData.put("showCondition", showCondition);
						
						pool.doResponse(uid, "UpdateTableDetails", buildFinalData(showCondition, receivedData));
					}
				} catch (GException e) {
					LogHelp.doLogAppErr(e);
				}
			}
		});
		return doResponseSucc(true);
	}
	
	public static Map<String, Object> buildFinalData(Integer condition, Map<String, Object> receivedData) {
		Map<String, Object> finalData = receivedData;
		if (condition == null || condition == 7) {//没有监控信息，全部返回
			//do nothing...
		}else {
			if (receivedData != null && receivedData.size() > 0 && receivedData.containsKey("users")) {
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> listForUsers = (List)receivedData.get("users");
				List<Map<String, Object>> listForItems = (List)receivedData.get("items");
				
				if (listForUsers != null && listForUsers.size() > 0) {
					
					List<Map<String, Object>> users = new ArrayList<>();
					List<Map<String, Object>> items = new ArrayList<>();
					for (Map<String, Object> map : listForUsers) {
						Integer role = (Integer) map.get("role");
						if (role != null) {
							if (((condition & 1) == 1 && role.intValue() == 1)||//需要用户
								(((condition >> 1) & 1) == 1 && role.intValue() == 2)||//需要管理员
								(((condition >> 2) & 1) == 1 && role.intValue() == 3)//需要机器人
								) {
								users.add(map);
								if (listForItems != null) {
									listForItems.forEach(item -> {
										if (map.get("uid").equals(item.get("uid"))) {
											items.add(item);
											return;
										}
									});
								}
							}
						}
					}
					
					if (users.size() > 0) {
						finalData.put("users", users);
						finalData.put("items", items);
					}else {
						finalData.remove("users");
						finalData.remove("items");
					}
				}
			}
		}
		return finalData;
	}

}
